package com.example.shop.utils;

import com.csvreader.CsvWriter;
import com.example.shop.bos.IBosSet;
import com.example.shop.domain.Order;
import com.example.shop.domain.OrderItem;
import com.example.shop.domain.Product;
import com.example.shop.enums.OrderStatusEnum;
import com.example.shop.service.ProductService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ExportExcelUtil {

    @Autowired
    private ProductService productService;

    @Value("${excelpath}")
    String excelpath;

    /**
     * 将指定的订单集合导出到excel表中,并修改订单的状态: 将新订单状态修改为已导出状态
     *
     * @param orderList 指定的订单集合
     * @param response
     */
    public void returnOrder(List<Order> orderList, HttpServletResponse response) {
        try {
            //设置文件路径 文件名
            File directory = new File(excelpath);
            File tempFile = File.createTempFile("vehicle", ".csv", directory);
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', Charset.forName("UTF-8"));

            //将数据转化为excel
            //TODO:导出3种不同状态订单的excel表:
            //TODO:导出商品时需要导出商品种类
            String[] headers = {"订单号", "姓名", "地址", "联系电话", "订单金额", "商品种类"};
            //todo 返回内容 需要进一步依据需求更改
            csvWriter.writeRecord(headers);
            for (Order order : orderList) {
                csvWriter.write(order.getNumber());
                csvWriter.write(order.getName());
                csvWriter.write(order.getAddress());
                csvWriter.write(order.getPhone());

                csvWriter.write(order.getAmount() + "分");

                //TODO:获得产品的数量
                Map<Product, Integer> map = order.getItems().stream().collect(Collectors.toMap(OrderItem::getProduct,
                        OrderItem::getCount));
                map.forEach((pro,count)-> {
                    try {
                        csvWriter.write(pro.getName() + "*" + count);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

//                Set<String> productIdSet = order.getItems().stream().map(orderItem -> orderItem.getProduct().getId()).collect
//                        (Collectors.toSet());
//                List<Product> productList = productService.findByIdIn(productIdSet);
//                for (int i = 0; i < productList.size(); i++) {
//                    String name = productList.get(i).getName();
//                    csvWriter.write(name + "*1");
//                }


                csvWriter.endRecord();

                //将订单状态修改为已导出状态
                order.setOrderStatus(OrderStatusEnum.EXPORT.getCode());

            }
            csvWriter.close();

            //将数据以流的形式返回
            response.reset();
            response.setContentType("application/ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename= " + tempFile.getCanonicalPath());
            response.flushBuffer();
            DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tempFile.getCanonicalPath()));
            int by;
            while ((by = bis.read()) != -1) {
                dos.write(by);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void returnProduct(List<Order> orderList, HttpServletResponse response) {
        try {
            //设置文件路径 文件名
            File directory = new File(excelpath);
            File tempFile = File.createTempFile("vehicle", ".csv", directory);
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', Charset.forName("UTF-8"));

            //将数据转化为excel
            String[] headers = {"订单号", "姓名", "地址", "联系电话", "订单金额"};
            //todo 返回内容 需要进一步依据需求更改
            csvWriter.writeRecord(headers);
            for (Order order : orderList) {
                csvWriter.write(order.getId());
                csvWriter.write(order.getName());
                csvWriter.write(order.getAddress());
                csvWriter.write(order.getPhone());


                csvWriter.write(order.getAmount() + "分");
                csvWriter.endRecord();
            }
            csvWriter.close();

            //将数据以流的形式返回
            response.reset();
            response.setContentType("application/ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename= " + tempFile.getCanonicalPath());
            response.flushBuffer();
            DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tempFile.getCanonicalPath()));
            int by;
            while ((by = bis.read()) != -1) {
                dos.write(by);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
